package com.llbnk.srb.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.llbnk.common.exception.Assert;
import com.llbnk.common.result.ResponseEnum;
import com.llbnk.srb.core.enums.BorrowInfoStatusEnum;
import com.llbnk.srb.core.enums.BorrowerStatusEnum;
import com.llbnk.srb.core.enums.UserBindEnum;
import com.llbnk.srb.core.mapper.BorrowInfoMapper;
import com.llbnk.srb.core.mapper.BorrowerMapper;
import com.llbnk.srb.core.mapper.IntegralGradeMapper;
import com.llbnk.srb.core.mapper.UserInfoMapper;
import com.llbnk.srb.core.pojo.entity.BorrowInfo;
import com.llbnk.srb.core.pojo.entity.Borrower;
import com.llbnk.srb.core.pojo.entity.IntegralGrade;
import com.llbnk.srb.core.pojo.entity.UserInfo;
import com.llbnk.srb.core.pojo.vo.BorrowInfoApprovalVO;
import com.llbnk.srb.core.pojo.vo.BorrowerDetailVO;
import com.llbnk.srb.core.service.BorrowInfoService;
import com.llbnk.srb.core.service.BorrowerService;
import com.llbnk.srb.core.service.DictService;
import com.llbnk.srb.core.service.LendService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 借款信息表 服务实现类
 * </p>
 *
 * @author llbnk
 * @since 2022-04-07
 */
@Service
@Slf4j
public class BorrowInfoServiceImpl extends ServiceImpl<BorrowInfoMapper, BorrowInfo> implements BorrowInfoService {

    //getBorrowAmount方法获取积分使用
    @Resource
    private UserInfoMapper userInfoMapper;

    //getBorrowAmount方法用来取出对应积分的借款额度
    @Resource
    private IntegralGradeMapper integralGradeMapper;

    //selectList方法里面使用连表查询查出借款列表数据
    @Resource
    private BorrowInfoMapper borrowInfoMapper;

    @Resource
    private DictService dictService;

    @Resource
    private BorrowerMapper borrowerMapper;

    @Resource
    private BorrowerService borrowerService;

    @Resource
    private LendService lendService;

    /**
     * 通过积分来获得对应借款金额
     * @param userId
     * @return
     */
    @Override
    public BigDecimal getBorrowAmount(Long userId) {

        //获取用户积分
        UserInfo userInfo = userInfoMapper.selectById(userId);
        //做用户校验（防止恶意用户绕过前面登录页面）
        Assert.notNull(userInfo, ResponseEnum.LOGIN_MOBILE_ERROR);
        Integer integral = userInfo.getIntegral();

        //根据积分查询额度
        QueryWrapper<IntegralGrade> integralGradeQueryWrapper = new QueryWrapper<>();
        integralGradeQueryWrapper
                //小于等于 <=
                .le("integral_start",integral)
                //大于等于 >=
                .ge("integral_end",integral);
        IntegralGrade integralGrade = integralGradeMapper.selectOne(integralGradeQueryWrapper);
        if(integralGrade == null){
            return new BigDecimal("0");
        }

        return integralGrade.getBorrowAmount();

    }

    /**
     * 把前端借款申请的页面数据传递保存在borrowInfo数据表中
     * @param borrowInfo 前端传进来的数据对应包装的实体类对象
     * @param userId 借款申请人id
     */
    @Override
    public void saveBorrowInfo(BorrowInfo borrowInfo, Long userId) {

        //获取userInfo信息
        UserInfo userInfo = userInfoMapper.selectById(userId);

        //判断用户绑定状态 断言判断，如果userInfo表中是已经绑定就不报错（防止恶意攻击）
        Assert.isTrue(
                userInfo.getBindStatus().intValue() == UserBindEnum.BIND_OK.getStatus().intValue(),
                ResponseEnum.USER_NO_BIND_ERROR
        );

        //判断借款人额度申请状态 断言判断，如果用户借款信息还没经过管理员审核就报错用户信息未审核（防止恶意攻击）
        Assert.isTrue(
                userInfo.getBorrowAuthStatus().intValue() == BorrowerStatusEnum.AUTH_OK.getStatus().intValue(),
                ResponseEnum.USER_NO_BIND_ERROR
        );

        //判断借款人额度是否充足 言判断，如果用户借款金额大于管理员给的金额范围（这个金额范围调用的是getBorrowAmount）
        //就报额度不足
        BigDecimal borrowAmount = this.getBorrowAmount(userId);
        Assert.isTrue(
                borrowInfo.getAmount().doubleValue() <= borrowAmount.doubleValue(),
                ResponseEnum.USER_AMOUNT_LESS_ERROR
        );

        //存储borrowInfo数据
        borrowInfo.setUserId(userId);
        //从前端页面传进来的是一个整数年利率12（%）我们存储在数据库中应该是0.12所以需要转化一下
        //但是这个getBorrowYearRate参数是bigDecimal所以需要下面的处理方法
        borrowInfo.setBorrowYearRate(borrowInfo.getBorrowYearRate().divide(new BigDecimal(100)));
        //将borrowInfo状态置为审核中（因为你这个申请的金额还需要后端管理员审核才行）
        borrowInfo.setStatus(BorrowInfoStatusEnum.CHECK_RUN.getStatus());
        System.out.println("****************************************");
        System.out.println("****************************************");
        log.info("开始添加新的数据进入borrowerInfo表");
        baseMapper.insert(borrowInfo);
        log.info("添加新的数据进入borrowerInfo表完成");
        System.out.println("****************************************");
        System.out.println("****************************************");


    }

    /**
     * 返回borrowInfo表的申请借款的审核状态
     * @param userId
     * @return
     */
    @Override
    public Integer getStatusByUserId(Long userId) {

        QueryWrapper<BorrowInfo> borrowInfoQueryWrapper = new QueryWrapper<>();
        borrowInfoQueryWrapper.select("status").eq("user_id",userId);
        List<Object> objects = baseMapper.selectObjs(borrowInfoQueryWrapper);
        if(objects.size() == 0 ){
            return BorrowInfoStatusEnum.NO_AUTH.getStatus();
        }
        Integer status = (Integer) objects.get(0);
        return status;
    }

    /**
     * 因为borrowInfo的实体类有加了几个字段，所以我们需要从borrow和borrowInfo两个表取数据
     * 两个表的共同点userId(这个地方需要自己写sql语句）
     * @return 具体都返回什么还需要看前端展示需求（借款列表）
     */
    @Override
    public List<BorrowInfo> selectList() {
        List<BorrowInfo> borrowInfoList = borrowInfoMapper.selectBorrowInfoList();

        borrowInfoList.forEach( borrowInfo ->{
            //存储在borrowInfo表中的数据字典只是需要需要调用dictService里之前写好的方法把对应的msg取出来
            String returnMethod = dictService.getNameByParentDictCodeAndValue("returnMethod", borrowInfo.getReturnMethod());
            String moneyUse = dictService.getNameByParentDictCodeAndValue("moneyUse", borrowInfo.getMoneyUse());
            String status = BorrowInfoStatusEnum.getMsgByStatus(borrowInfo.getStatus());
            borrowInfo.getParam().put("returnMethod", returnMethod);
            borrowInfo.getParam().put("moneyUse", moneyUse);
            borrowInfo.getParam().put("status", status);
        });
        return borrowInfoList;
    }

    @Override
    public Map<String, Object> getBorrowInfoDetail(Long id) {

        //查询借款对象
        BorrowInfo borrowInfo = baseMapper.selectById(id);
        //组装数据
        String returnMethod = dictService.getNameByParentDictCodeAndValue("returnMethod", borrowInfo.getReturnMethod());
        String moneyUse = dictService.getNameByParentDictCodeAndValue("moneyUse", borrowInfo.getMoneyUse());
        String status = BorrowInfoStatusEnum.getMsgByStatus(borrowInfo.getStatus());
        borrowInfo.getParam().put("returnMethod", returnMethod);
        borrowInfo.getParam().put("moneyUse", moneyUse);
        borrowInfo.getParam().put("status", status);

        //根据user_id获取借款人对象
        QueryWrapper<Borrower> borrowerQueryWrapper = new QueryWrapper<Borrower>();
        borrowerQueryWrapper.eq("user_id", borrowInfo.getUserId());
        Borrower borrower = borrowerMapper.selectOne(borrowerQueryWrapper);
        //组装借款人对象
        BorrowerDetailVO borrowerDetailVO = borrowerService.getBorrowerDetailVOById(borrower.getId());

        //组装数据
        Map<String, Object> result = new HashMap<>();
        result.put("borrowInfo", borrowInfo);
        result.put("borrower", borrowerDetailVO);
        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void approval(BorrowInfoApprovalVO borrowInfoApprovalVO) {

        //修改借款信息状态
        Long borrowInfoId = borrowInfoApprovalVO.getId();
        BorrowInfo borrowInfo = baseMapper.selectById(borrowInfoId);
        borrowInfo.setStatus(borrowInfoApprovalVO.getStatus());
        baseMapper.updateById(borrowInfo);

        //审核通过则创建标的
        if (borrowInfoApprovalVO.getStatus().intValue() == BorrowInfoStatusEnum.CHECK_OK.getStatus().intValue()) {
            //创建标的
            //TODO
            lendService.createLend(borrowInfoApprovalVO, borrowInfo);
        }
    }
}
